<template>
    <div>
        <!--面包屑-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>活动管理</el-breadcrumb-item>
            <el-breadcrumb-item>活动列表</el-breadcrumb-item>
            <el-breadcrumb-item>活动详情</el-breadcrumb-item>
        </el-breadcrumb>
        <!--搜索功能-->
        <div class="line-h60" style="margin-top: 5px;">
            <el-col :span="10">
                <el-input placeholder="请输入内容" v-model="searchData" class="input-with-select ">
                    <el-button slot="append" icon="el-icon-search" @click.stop="searchGet"></el-button>
                </el-input>

            </el-col>

            <el-col :span="5">
                <el-button type="primary" plain @click="addUserShow = true">添加用户</el-button>
            </el-col>
        </div>
        <!--表格-->
        <el-table
                class="line-h60  el-table"
                ref="singleTable"
                :data="tableData"
                border
                highlight-current-row
                @current-change="handleCurrentChange"
                style="width: 100%">
            <el-table-column
                    type="index"
                    width="50">
            </el-table-column>

            <el-table-column
                    property="username"
                    label="姓名"
                    width="120"
            >
            </el-table-column>
            <el-table-column
                    property="email"
                    label="邮箱"
            >
            </el-table-column>
            <el-table-column
                    property="mobile"
                    label="电话"
            >
            </el-table-column>

            <el-table-column
                    property="kk"
                    label="状态"
            >

                <template slot-scope="scope"> <!--作用域插槽。重要。要加这个slot-scope否则单个按钮不能连续切换-->
                    <el-switch
                            v-model="scope.row.mg_state"
                            active-color="#13ce66"
                            inactive-color="#ff4949"
                            @change="changeswitch(scope)">
                    </el-switch>
                </template>
            </el-table-column>

            <el-table-column
                    label="状态"
            >   <!--个人理解里面是插槽，这样每个表格元素但与昂都有了-->
                <!--:disabled必须绑定布尔值。可以写data里面的值，也可以直接true。都是引号内部直接代表里面是表达式-->
                <template slot-scope="scope">
                    <!--编辑用户信息-->
                    <el-button size="mini" :autofocus="false" type="primary" plain icon="el-icon-edit" @click="editUserShowwin(scope)"></el-button>
                    <!--删除用户-->
                    <el-button class="select-btn" type="danger" plain icon="el-icon-delete" @click="deleteuser(scope)"></el-button>
                    <!--修改用户角色-->
                    <el-button class="select-btn" type="warning" plain icon="el-icon-check" @click="roleUserShowwin(scope)"></el-button>

                </template>
            </el-table-column>

        </el-table>
        <!--分页器-->
        <div class="block">

            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="pHandleCurrentChange"
                    :current-page="1"
                    :page-sizes="[1, 2, 4, 10]"
                    :page-size="10"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>
        <!--弹窗出来添加用户-->
        <el-dialog title="添加新用户" :visible.sync="addUserShow" >
            <el-form :model="addform" ref="adduser" :rules="rules" :status-icon="value">
                <el-form-item label="用户名称" :label-width="formLabelWidth"   prop="name">
                    <el-input v-model="addform.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="用户密码" :label-width="formLabelWidth" prop="pwd">
                    <el-input v-model="addform.pwd" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
                    <el-input v-model="addform.email" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="手机号" :label-width="formLabelWidth">
                    <el-input v-model="addform.mobile" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addUserShow = false">取 消</el-button>
                <el-button type="primary" @click="incrementUser">确 定</el-button>
            </div>
        </el-dialog>
            <!--弹窗修改用户-->
        <el-dialog title="编辑用户" :visible.sync="editUserShow">
            <el-form :model="editform" ref="editUser" :rules="rules" :status-icon="value">
                <el-form-item label="用户名称"  :label-width="formLabelWidth" prop="name">
                    <el-input v-model="editform.username" :disabled="true" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
                    <el-input v-model="editform.email" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="手机号" :label-width="formLabelWidth">
                    <el-input v-model="editform.mobile" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="qiaoxiaoxiugai">取 消</el-button>
                <el-button type="primary" @click="editUser">确 定</el-button>
            </div>
        </el-dialog>
        <!--弹窗修改用户角色-->
        <el-dialog title="修改用户角色" :visible.sync="roleUserShow">
            <el-form :model="roleUserData" ref="roleUserData" :rules="rules" :status-icon="value">
                <el-form-item label="用户名称"  :label-width="formLabelWidth" prop="name">
                    <!--<div class="userrole"> {{this.roleUserData.username}} </div>-->
                    <el-input v-model="roleUserData.username" :disabled="true" autocomplete="off"></el-input>
                </el-form-item>

                <el-form-item label="用户角色"  :label-width="formLabelWidth" >
                    <el-select v-model="roleId" placeholder="请选择">
                        <el-option
                                v-for="item in roleList"
                                :key="item.id"
                                :label="item.roleName"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.stop="roleUserShow=false">取 消</el-button>
                <el-button type="primary" @click.stop="roleUserPut">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
    export default {
        name: "users",
        data() {
            return {
                total:0,//所有用户数量
                pageSize:10,//单页用户数量，默认为10
                pagenum:1,//展示的页码，默认为第一页
                searchData: '',
                tableData: [],
                currentRow: null,
                value: true,

                addUserShow: false,//是否添加用户弹窗
                addform: {
                    name: '',
                    pwd: '',
                    email: '',
                    mobile: '',
                },
                editUserShow:false,//是否编辑用户信息弹窗
                editform: {
                    name: '',
                    email: '',
                    mobile: '',
                    id:''
                },
                roleUserShow:false,//是否修改用户角色
                roleList:[],
                roleId:'',
                roleUserData:{},
                formLabelWidth: '120px',
                rules: {
                    name: [
                        {required: true, message: '请输要添加的新用户名称', trigger: 'blur'},
                        {min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'}
                    ],
                    pwd: [
                        {required: true, message: '请输要添加的新用户密码', trigger: 'blur'},
                    ],
                    email: [
                        {required: true, message: '请输要添加的新用户邮箱哦', trigger: 'blur'},
                    ]
                }

            }
        },
        methods: {
            //获取用户信息列表
            getUsersData(query = '') {
                var url;
                if (query === '') {
                    url = 'users?pagenum='+this.pagenum+'&pagesize='+this.pageSize
                } else {
                    url = 'users?pagenum='+this.pagenum+'&pagesize='+this.pageSize+'&query=' + query;
                }

                this.$myhttp({
                    url: url,
                    method: 'get',
                    //headers:{Authorization:localStorage.getItem('token')}
                }).then((respon) => {
                    let {data, meta} = respon.data;

                    if (meta.status === 200) {
                        console.log('获取成功');
                        console.log(respon,'得到用户信息');//得到用户信息，解构赋值到this.tableData
                        this.total=data.total;//total是指总共的用户数量。与users不一致。users只是指定页码的数据
                        this.tableData = data.users
                    }
                })
            },
            searchGet() { //通过搜索框关键字模糊搜索得到匹配用户信息列表
                this.getUsersData(this.searchData)
            },
            //添加新用户
            incrementUser() {
                this.$refs.adduser.validate((err) => {
                    if (!err) {  //表单验证方法
                        console.log(err, 'hhhhhhhh');
                        console.log('哈哈哈哈新增用户错误');
                        return;
                    }
                });

                this.$myhttp({
                    method: 'post',
                    url: 'users',
                    data: {
                        username: this.addform.name,
                        password: this.addform.pwd,
                        email: this.addform.email,
                        mobile: this.addform.mobile
                    }
                }).then((respon) => {
                    let {data, meta} = respon.data;

                    //console.log('添加用户成功1',data,meta);
                    if (meta.status === 201) {//这里post成功是201注意了，所有要先打印看看meta
                        console.log('添加用户成功2', data, meta);
                        console.log(respon);//得到用户信息，解构赋值到this.tableData
                        //this.tableData =data.users
                        this.$message({
                            message: '恭喜你添加用户成功',
                            type: 'success'
                        });
                        this.getUsersData()
                    }

                });
                this.addUserShow = false

            },
            //切换用户状态
            changeswitch(scope) {
                // console.log(scope,"切换状态",this.tableData);
                //console.log(scope.row.mg_state,'对比');
                let obj1 = [];
                console.log(obj1);
                //当按钮一按就会立即切换true和false，scope其实就已经变成切换后的值。scope来源于tableData
                this.$myhttp({
                    url: `users/${scope.row.id}/state/${scope.row.mg_state}`,
                    method: 'put',
                    //headers:{Authorization:window.localStorage.getItem('token1')}//假设网络出错，无法发送正确token
                }).then((respon) => {
                    //console.log(respon,'修改成功');
                    let {data, meta} = respon.data;
                    if (meta.status === 200) {
                        this.$message({
                            message: '修改用户状态成功',
                            type: 'success'
                        });
                    } else {
                        //console.log(scope.row.mg_state,'对比')//如果断网则切换后瞬间切回，使用户无法更改状态
                        this.tableData[scope.$index].mg_state = !scope.row.mg_state
                    }
                })
            },
            //删除用户
            deleteuser(scope) {
                console.log(scope);
                this.$confirm('此操作将永久删除该用户吗, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {

                    this.$myhttp({
                        url: `users/${scope.row.id}`,
                        method: 'delete'
                    }).then((respon) => {
                        let {data, meta} = respon.data;
                        if (meta.status === 200) {//假如成功删除
                            this.getUsersData();
                            this.$message({
                                message: '成功删除用户',
                                type: 'success'
                            });
                        }
                    })

                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            //弹窗修改用户信息对话框
            editUserShowwin(scope){
               // console.log(scope,'哈哈哈');
                this.editUserShow=true;//显示弹窗
                //接收点击时候传入的scope数据，赋值到editform
                this.editform=scope.row;//也可以直接全部赋值
               // console.log(scope.row,'jjjj')
                //涉及到堆的指向问题。editform来自于scope，指向这个堆，当editform改变时候其实也直接改变了堆
                //而下面这种不行，不能实时更新
                // this.editform.name=scope.row.username;
                // this.editform.email=scope.row.email;
                // this.editform.mobile=scope.row.mobile;
                // this.editform.id=scope.row.id
            },
            //修改用户信息
            editUser(){
                this.$refs.editUser.validate((err)=>{//如果验证有误直接不进行下面接口请求工作
                    if(!err){
                        console.log(err)
                        return
                    }
                });
                //请求接口：修改用户信息
                    this.$myhttp({
                        url:`users/${this.editform.id}`,
                        method:'put',
                        data:{id:this.editform.id,
                               email: this.editform.email,
                               mobile: this.editform.mobile,
                            }
                    }).then((respon)=>{
                        let {data,meta}=respon.data;
                       // console.log(data,meta);
                        if(meta.status===200){
                            this.getUsersData();//重新获取用户信息，刷新
                            this.editUserShow=false;//关闭修改用户信息的窗口
                            this.$message({
                                message: '成功修改用户信息',
                                type: 'success'
                            });
                        }else{
                            this.$message({
                                message: '修改用户信息失败',
                                type: 'error'
                            });
                        }

                    })

            },
            //取消修改用户信息
            qiaoxiaoxiugai(){
                this.getUsersData();
                this.editUserShow=false;
                this.$message({
                    message: '您取消了修改用户信息',
                    type: 'error'
                });
            },
            //弹窗 修改用户角色对话框
            roleUserShowwin(scope){
                this.roleUserShow=true;//打开修改角色窗口
                this.roleUserData=scope.row;
               // console.log(scope,'jjjjj')
                //获取角色列表
                this.$myhttp({
                    url:"roles",
                    method:'get'
                }).then((respon)=>{
                    let {data,meta}=respon.data;
                   // console.log(data,meta);
                    if(meta.status===200){
                        this.roleList=data;
                    }
                })

            },
            //修改用户角色
            roleUserPut(){
                this.$myhttp({
                    url:`users/${this.roleUserData.id}/role`,
                    method:'put',
                    data:{
                        id:this.roleUserData.id,
                        rid:this.roleId
                    }
                }).then((respon)=>{
                    let {data,meta}=respon.data;
                    if(meta.status===200){
                       console.log(data);
                        //this.roleId=data.rid;
                       // console.log("修改角色成功",this.roleId);
                        this.$message({
                            message:"修改用户角色成功",
                            type:"success"
                        })
                    }
                });
                //关闭角色修改窗口
                this.roleUserShow =false;
            },

            setCurrent(row) {
                this.$refs.singleTable.setCurrentRow(row);
            },
            handleCurrentChange(val) {
                this.currentRow = val;
            },
            handleSizeChange(pageSize) {//参数为回调参数，自动的，不需要在标签里面传入。
                console.log(`每页 ${pageSize} 条`);
                this.pageSize=pageSize;
                this.getUsersData();
            },
            pHandleCurrentChange(val) {
                console.log(`当前页: ${val}`);////参数为回调参数，自动的，不需要在标签里面传入。
                this.pagenum=val;
                this.getUsersData();
            }
        },
        mounted() {
            this.getUsersData();
            // console.log(localStorage.getItem('token'))
            // var aa=prompt("请输入姓名");
            // console.log(aa);
            //  var aa=this.$prompt("需要输入点东西","中国");
            //  console.log(aa)
        }
    }
</script>

<style>
    /*.line-h60{*/
    /*line-height:60px;*/
    /*text-align:center;*/
    /*}*/
    /*不能加scoped会失效范围限制*/
    .el-main {
        line-height: 60px !important;
    }

    .el-table td, .el-table th {
        text-align: center !important;

    }

    .select-btn {
        padding: 2px 5px !important;
    }
    .uesrrole{
        text-align:left;
    }
    /*表单验证正确显示绿色小对勾，添加用户*/
    .el-icon-circle-check{
        color:green;
        font-weight:700 !important;
    }
</style>
